package com.tangsm.spring.boot.aliyun.bailian.exception;

import com.tangsm.spring.boot.aliyun.bailian.model.Result;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        String errorMsg = ex.getBindingResult().getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return Result.error(400, errorMsg);
    }

    // 处理JSON解析异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<?> handleJsonParseException(HttpMessageNotReadableException ex) {
        return Result.error(400, "请求体JSON格式错误");
    }

    // 处理业务层异常
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<?> handleBusinessException(IllegalArgumentException ex) {
        return Result.error(400, ex.getMessage());
    }

    // 处理其他未捕获异常
    @ExceptionHandler(Exception.class)
    public Result<?> handleOtherExceptions(Exception ex) {
        return Result.error(500, "系统繁忙，请稍后再试");
    }
}